package com.wenjh.jdmzt.service;

import java.util.List;

import android.database.sqlite.SQLiteDatabase;

import com.wenjh.jdmzt.AndroidKit;
import com.wenjh.jdmzt.service.dao.ImageDao;
import com.wenjh.jdmzt.service.model.Image;

public class ImageService {
	ImageDao imageDao = null;
	SQLiteDatabase db = null;
	
	public ImageService() {
		db = AndroidKit.getApp().getSqliteInstance();
		imageDao = new ImageDao(db);
	}
	
	public void saveImage(List<Image> images) {
		try {
			db.beginTransaction();
			imageDao.deleteAll();
			for (Image image : images) {
				imageDao.insert(image);
			}
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
		
		AndroidKit.saveCache("imagelist", images);
	}
	
	@SuppressWarnings("unchecked")
	public List<Image> findImages() {
		if(AndroidKit.getCache("imagelist") != null) {
			return (List<Image>) AndroidKit.getCache("imagelist");
		}
		return imageDao.getAll();
	}
	
	public void addImages(List<Image> images) {
		try {
			db.beginTransaction();
			for (Image image : images) {
				if(imageDao.checkExsit(image.getId())) {
					imageDao.update(image);
				} else {
					imageDao.insert(image);
				}
			}
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
		
		if(AndroidKit.getCache("imagelist") != null) {
			@SuppressWarnings("unchecked")
			List<Image> list = (List<Image>) AndroidKit.getCache("imagelist");
			list.addAll(images);
		}
	}
}
